import pandas as pd

def extract_merchant_features(file_path):
    """提取用户与商家交互的特征"""
    # 加载数据
    df = pd.read_csv(file_path)

    # 计算用户在商家的交互次数
    user_merchant_interactions = df.groupby(['user_id', 'merchant_id']).size().reset_index(
        name='用户在商家的交互次数')

    # 计算用户对商家的【商品、品类、品牌】的交互次数
    user_merchant_item_interactions = df.groupby(['user_id', 'merchant_id', 'item_id']).size().reset_index(
        name='用户对商家商品的交互次数')
    user_merchant_cat_interactions = df.groupby(['user_id', 'merchant_id', 'cat_id']).size().reset_index(
        name='用户对商家品类的交互次数')
    user_merchant_brand_interactions = df.groupby(['user_id', 'merchant_id', 'brand_id']).size().reset_index(
        name='用户对商家品牌的交互次数')

    # 计算用户对商家【点击、加购物车、购买、收藏】的次数
    action_counts = df.groupby(['user_id', 'merchant_id', 'action_type']).size().unstack(fill_value=0)
    action_counts.columns = ['点击次数', '加购物车次数', '购买次数', '收藏次数']
    action_counts = action_counts.reset_index()

    # 将 time_stamp 转换为日期格式
    df['time_stamp'] = pd.to_datetime(df['time_stamp'], format='%m%d').dt.strftime('%m-%d')

    # 计算不同用户在不同商家购买率
    total_actions = df.groupby(['user_id', 'merchant_id']).size().reset_index(name='总交互次数')
    purchase_actions = df[df['action_type'] == 2].groupby(['user_id', 'merchant_id']).size().reset_index(
        name='购买次数')

    # 合并并计算购买率
    purchase_rate = pd.merge(total_actions, purchase_actions, on=['user_id', 'merchant_id'], how='left')
    purchase_rate['购买率'] = purchase_rate['购买次数'] / purchase_rate['总交互次数']
    purchase_rate['购买率'] = purchase_rate['购买率'].fillna(0)
    purchase_rate = purchase_rate[['user_id', 'merchant_id', '购买率']]

    # 合并结果
    result = user_merchant_interactions
    for df_to_merge in [user_merchant_item_interactions, user_merchant_cat_interactions,
                        user_merchant_brand_interactions, action_counts,  purchase_rate]:
        result = pd.merge(result, df_to_merge, on=['user_id', 'merchant_id'], how='left')

    # 填充所有NaN值为0
    result = result.fillna(0)

    return result


# 使用示例
if __name__ == "__main__":
    file_path = '../balanced_data.csv'
    features_result = extract_merchant_features(file_path)
    print(features_result.head())

columns_to_drop = ['user_id', 'item_id', 'cat_id']

# 删除指定列
features_result = features_result.drop(columns_to_drop, axis=1)

print(f"去重前行数: {len(features_result)}")
features_result = features_result.drop_duplicates()
print(f"去重后行数: {len(features_result)}")

# 保存结果，指定编码为 utf-8-sig 防止乱码
csv_path = '商家data_features.csv'
features_result.to_csv(csv_path, encoding='utf-8-sig', index=False)

# # 合并表
# user = pd.read_csv('../特征工程/用户data_features.csv')
# user_merchant = pd.read_csv('../特征工程/用户和商家data_features.csv')
# merchant = pd.read_csv('../特征工程/商家data_features.csv')
#
# # 三个表都有user_id和merchant_id作为共同键
# merged_1 = pd.merge(
#     user_merchant,  # 左表
#     user,           # 右表
#     on='user_id',   # 连接键
#     how='left'      # 左连接，保留user_merchant中的所有记录
# )
#
# # 2. 将合并结果与merchant表合并（基于merchant_id）
# final_data = pd.merge(
#     merged_1,       # 左表（上次合并的结果）
#     merchant,       # 右表
#     on='merchant_id',  # 连接键
#     how='left'      # 左连接，保留user_merchant中的所有记录
# )
#
# print(final_data.head())